package com.niji.littly_donkey_android.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.android.volley.*;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.http.CustomApplication;
import com.niji.littly_donkey_android.http.PostStringRequest;
import com.niji.littly_donkey_android.util.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity {

    private static final String TAG = "LoginActivity";

    private ImageButton login_return;

    private Button btn_login;

    private TextView login_phone;

    private EditText edit_login_phone;

    private Handler handler = new Handler();
    private Runnable runnable;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        init();
        loginReturn();
        getPhoneCode();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.login_activity;

    }
    @Override
    protected int getStatusBarColor() {
        return R.color.white_easy_photos;
    }

    private void init() {
        login_phone = findViewById(R.id.login_phone);
        Intent intent = getIntent();
        String phone = intent.getStringExtra("phone");
        login_phone.setText("验证码已通过短信发送至 " + phone);
    }

    /**
     * 获取短信验证码
     */
    private void getPhoneCode() {
        edit_login_phone = findViewById(R.id.edit_login_code);
        btn_login = findViewById(R.id.btn_login);
        edit_login_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (runnable != null) {
                    handler.removeCallbacks(runnable);
                }
                runnable = new Runnable() {
                    @Override
                    public void run() {
                        //结束后进行操作
                        String code = edit_login_phone.getText().toString().trim();
                        Intent intent = getIntent();
                        if (code.length() != 6) {
                            Toast.makeText(LoginActivity.this, "验证码错误，请重试", Toast.LENGTH_SHORT).show();

                        }else {
                            btn_login.setClickable(true);
                            btn_login.setBackgroundColor(Color.parseColor("#4258d0"));
                        }
                    }
                };
                handler.postDelayed(runnable, 1000);

            }
        });

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_login.setClickable(true);
                Intent intent1 = getIntent();
                String phone = intent1.getStringExtra("phone");
                String code = edit_login_phone.getText().toString().trim();
                String url = UrlUtil.URL + "/login";
                Map<String, String> map = new HashMap<>();
                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Log.i(TAG, s.toString());
                        try {
                            Map<String, Object> map = JsonUtil.jsonToMap(s.toString());


                            Map<String, Object> data = (Map<String, Object>) map.get("data");
                            Boolean isRegister = (Boolean) data.get("isRegister");
                            if (isRegister) {
                                String userInfo = data.get("userInfo").toString();
                                Intent intent = new Intent(LoginActivity.this, IndexActivity.class);
                                intent.putExtra("userInfo", userInfo);
                                startActivity(intent);
                                finish();
                            } else {
                                Intent intent = new Intent(LoginActivity.this, InfoActivity.class);
                                intent.putExtra("phone", phone);
                                intent.putExtra("code", code);
                                startActivity(intent);
                                finish();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println("text");
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                })
                {

                    @Override
                    protected Response<String> parseNetworkResponse(NetworkResponse response) {

                        String sesseionid = new ConnectViaSession(LoginActivity.this).GetSession();
                        new ConnectViaSession(LoginActivity.this).getSession(response);
                        return super.parseNetworkResponse(response);
                    }

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<>();
                        map.put("phone",phone);
                        map.put("code",code);
                        return map;
                    }
                };
//
//                }
//                {
//                    @Override
//                    public Map<String, String> getHeaders() throws AuthFailureError {
//                        String sesseionid = new ConnectViaSession(LoginActivity.this).GetSession();
//                        if (!sesseionid.equals("")) {
//                            HashMap<String, String> headers = new HashMap<String, String>();
//                            headers.put("cookie", sesseionid);
//                            startActivity(new Intent(LoginActivity.this,IndexActivity.class));
//                            return headers;
//                        } else {
//                            Map<String, String> headers = super.getHeaders();
//                            String rawCookies = headers.get("Set-Cookie");
//                            //;分隔获取sessionid
//                            String sesstionID = rawCookies.split(";")[0];
//                            new ConnectViaSession(LoginActivity.this).SaveSession(sesstionID);
//                            return super.getHeaders();
//                        }
//                    }};

                requestQueue.add(stringRequest);
            }
        });

    }


    /**
     * 登录界面返回
     */
    private void loginReturn() {
        login_return = findViewById(R.id.login_return);
        login_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overridePendingTransition(R.anim.xpage_slide_in_left,R.anim.xpage_slide_out_right);
                finish();

            }
        });

    }
}
